package cn.theten52.demo.patterns.design.behavior.interpreter;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * 客户端
 *
 * @author wangjin
 * @date 2021/1/6
 */
public class Client {
    /**
     * 运行程序
     */
    public void run() {
        String exp = getExp();
        Map<String, Double> var = getValues(exp);
        Calculator calculator = new Calculator(exp);
        System.out.printf("%s = %f", exp, calculator.cal(var));
    }

    /**
     * 要求用户输入表达式
     *
     * @return 用户输入的表达式
     */
    private String getExp() {
        Scanner sc = new Scanner(System.in);
        System.out.println("please defined an expression:");
        return sc.nextLine();
    }

    /**
     * 要求用户输入每个变量的值
     *
     * @param exp 表达式
     * @return 获取表达式的值
     */
    private Map<String, Double> getValues(String exp) {
        Map<String, Double> map = new HashMap<>();
        Scanner sc = new Scanner(System.in);
        char[] chars = exp.toCharArray();
        for (char c : chars) {
            String str = String.valueOf(c);
            if (!"+-".contains(str) && !map.containsKey(str)) {
                System.out.printf("%s = ", str);
                map.put(str, sc.nextDouble());
            }
        }
        return map;
    }
}

class Test {
    public static void main(String[] args) {
        Client client = new Client();
        client.run();
    }
}
